<template>
  <div class="adoption-post-container">
    <!-- 搜索和操作栏 -->
    <div class="search-container" style="display: flex; align-items: center; justify-content: space-between;">
      <el-button type="success" @click="handleAdd" class="add-btn">
        <el-icon><Plus /></el-icon>发布领养信息
      </el-button>

      <div style="display: flex; align-items: center; gap: 10px;">
        <el-input v-model="searchQuery.name" placeholder="请输入宠物名称" clearable style="width: 200px" />
        <el-select v-model="searchQuery.status" placeholder="领养状态" clearable style="width: 150px">
          <el-option label="待领养" value="available" />
          <el-option label="已领养" value="adopted" />
          <el-option label="已下架" value="offline" />
        </el-select>
        <el-select v-model="searchQuery.type" placeholder="宠物类型" clearable style="width: 150px">
          <el-option 
            v-for="type in petTypes" 
            :key="type.id" 
            :label="type.type" 
            :value="type.id"
          />
        </el-select>
        <el-button type="primary" @click="handleSearch" class="search-btn">
          <el-icon><Search /></el-icon>搜索
        </el-button>
        <el-button type="danger" @click="handleClear" class="clear-btn">
          <el-icon><Delete /></el-icon>清除
        </el-button>
      </div>
    </div>

    <!-- 领养贴列表 -->
    <el-table v-loading="loading" :data="postList" class="custom-table" border stripe>
      <el-table-column label="ID" prop="id" width="80" align="center" />
      <el-table-column label="宠物照片" width="120" align="center">
        <template #default="scope">
          <el-image 
            :src="`/api/Petfile/${scope.row.image}`"
            class="pet-image" 
            fit="cover"
            :preview-src-list="[`/api/Petfile/${scope.row.image}`]"
            :hide-on-click-modal="false"
            preview-teleported
          >
            <template #error>
              <el-icon><Picture /></el-icon>
            </template>
          </el-image>
        </template>
      </el-table-column>
      <el-table-column label="宠物名称" prop="pet_name" min-width="120" align="center" />
      <el-table-column label="类型" prop="petTypeName" width="100" align="center">
        <template #default="scope">
          <el-tag :type="warning" class="pet-type-tag">
            {{ scope.row.petTypeName }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="年龄" prop="age" width="100" align="center">
        <template #default="scope">
          {{ scope.row.age }}岁
        </template>
      </el-table-column>
      <el-table-column label="性别" prop="gender" width="80" align="center">
        <template #default="scope">
          <el-tag :type="scope.row.gender === 'male' ? 'primary' : 'danger'" size="small">
            {{ scope.row.gender === 'male' ? '公' : '母' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="状态" prop="status" width="100" align="center">
        <template #default="scope">
          <el-tag :type="
            scope.row.status === 'available' ? 'success' :
            scope.row.status === 'adopted' ? 'primary' : 'danger'
          ">
            {{ 
              scope.row.status === 'available' ? '待领养' :
              scope.row.status === 'adopted' ? '已领养' : '已下架'
            }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="发布时间" prop="created_at" width="180" align="center">
        <template #default="scope">
          {{ formatDate(scope.row.created_at) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="350" align="center" fixed="right">
        <template #default="scope">
          <div style="display: flex; justify-content: center; gap: 10px;">
            <el-button type="info" size="small" @click="handleView(scope.row)" class="view-btn">
              <el-icon><View /></el-icon>查看
            </el-button>
            <el-button type="primary" size="small" @click="handleEdit(scope.row)" class="edit-btn">
              <el-icon><Edit /></el-icon>编辑
            </el-button>
            <el-button 
              :type="scope.row.status === 'offline' ? 'success' : 'warning'" 
              size="small" 
              @click="handleStatusChange(scope.row)"
              class="status-btn"
            >
              <el-icon>
               <Upload v-if="scope.row.status === 'offline'" />
               <Download v-else />
              </el-icon>
              {{ scope.row.status === 'offline' ? '上架' : '下架' }}
            </el-button>
            <el-button type="danger" size="small" @click="handleDelete(scope.row)" class="delete-btn">
              <el-icon><Delete /></el-icon>删除
            </el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[5, 10, 15, 20]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        background
      />
    </div>

    <!-- 添加/编辑对话框 -->
    <el-dialog
      :title="dialogType === 'add' ? '发布领养信息' : '编辑领养信息'"
      v-model="dialogVisible"
      width="650px"
      :close-on-click-modal="false"
    >
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="宠物照片" prop="image">
          <el-upload
            class="pet-uploader"
            action="/api/Petfile/upload"
            :show-file-list="false"
            :on-success="handleImageSuccess"
            :before-upload="beforeImageUpload"
            :on-remove="handleImageRemove"
          >
            <img v-if="form.image" :src="`/api/Petfile/${form.image}`" alt="宠物照片" class="pet-image" />
            <el-icon v-else><Plus /></el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="宠物名称" prop="pet_name">
          <el-input v-model="form.pet_name" placeholder="请输入宠物名称" />
        </el-form-item>
        <el-form-item label="宠物类型" prop="pet_type_id">
          <el-select v-model="form.pet_type_id" placeholder="请选择宠物类型" style="width: 100%">
            <el-option 
              v-for="type in petTypes"
              :key="type.id"
              :label="type.type"
              :value="type.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="年龄" prop="age">
          <el-input-number v-model="form.age" :min="0" :max="20" style="width: 100%" />
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-radio-group v-model="form.gender">
            <el-radio label="male">公</el-radio>
            <el-radio label="female">母</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="性格特点" prop="pet_character">
          <el-input type="textarea" v-model="form.pet_character" rows="3" placeholder="请描述宠物的性格特点" />
        </el-form-item>
        <el-form-item label="领养要求" prop="requirements">
          <el-input type="textarea" v-model="form.requirements" rows="3" placeholder="请填写领养要求" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false" class="cancel-btn">取消</el-button>
          <el-button type="primary" @click="handleSubmit" class="submit-btn">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 查看详情对话框 -->
    <el-dialog
      title="领养信息详情"
      v-model="detailDialogVisible"
      width="800px"
      class="detail-dialog"
    >
      <div class="detail-content">
        <div class="detail-left">
          <el-image
            :src="`/api/Petfile/${detailData.image}`"
            fit="cover"
            :preview-src-list="[`/api/Petfile/${detailData.image}`]"
            class="detail-image"
          >
            <template #error>
              <div class="image-error">
                <el-icon><Picture /></el-icon>
              </div>
            </template>
          </el-image>
          <div class="pet-status">
            <el-tag :type="
              detailData.status === 'available' ? 'success' :
              detailData.status === 'adopted' ? 'primary' : 'danger'
            " size="large">
              {{ 
                detailData.status === 'available' ? '待领养' :
                detailData.status === 'adopted' ? '已领养' : '已下架'
              }}
            </el-tag>
          </div>
        </div>
        <div class="detail-right">
          <h3 class="pet-name">{{ detailData.pet_name }}</h3>
          <div class="info-grid">
            <div class="info-item">
              <span class="label">宠物类型</span>
              <el-tag :type="warning" class="pet-type-tag">
                {{ detailData.petTypeName }}
              </el-tag>
            </div>
            <div class="info-item">
              <span class="label">年龄</span>
              <el-tag type="success">{{ detailData.age }}岁</el-tag>
            </div>
            <div class="info-item">
              <span class="label">性别</span>
              <el-tag :type="detailData.gender === 'male' ? 'primary' : 'danger'">
                {{ detailData.gender === 'male' ? '公' : '母' }}
              </el-tag>
            </div>
          </div>
          <div class="info-section">
            <h4>性格特点</h4>
            <p class="description">{{ detailData.pet_character || '暂无描述' }}</p>
          </div>
          <div class="info-section">
            <h4>领养要求</h4>
            <p class="description">{{ detailData.requirements || '暂无要求' }}</p>
          </div>
          <div class="time-info">
            <div class="time-item">
              <span class="time-label">发布时间</span>
              <span class="time-value">{{ formatDate(detailData.created_at) }}</span>
            </div>
            <div class="time-item">
              <span class="time-label">更新时间</span>
              <span class="time-value">{{ formatDate(detailData.updated_at) }}</span>
            </div>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Plus, 
  Search, 
  Edit, 
  Delete, 
  Picture, 
  View,
  Upload,
  Download
} from '@element-plus/icons-vue'
import request from '@/utils/request'

// 列表数据
const loading = ref(false)
const postList = ref([])
const currentPage = ref(1)
const pageSize = ref(5)
const total = ref(0)
const petTypes = ref([])

// 搜索条件
const searchQuery = reactive({
  name: '',
  status: '',
  type: ''
})

// 对话框控制
const dialogVisible = ref(false)
const dialogType = ref('add')
const formRef = ref(null)
const detailDialogVisible = ref(false)
const detailData = ref({})

// 表单数据
const form = reactive({
  id: null,
  pet_name: '',
  pet_type_id: null,
  age: 0,
  gender: 'male',
  pet_character: '',
  requirements: '',
  image: '',
  status: 'available'
})

// 表单验证规则
const rules = {
  pet_name: [
    { required: true, message: '请输入宠物名称', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  pet_type_id: [
    { required: true, message: '请选择宠物类型', trigger: 'change' }
  ],
  age: [
    { required: true, message: '请输入年龄', trigger: 'blur' }
  ],
  gender: [
    { required: true, message: '请选择性别', trigger: 'change' }
  ],
  image: [
    { required: true, message: '请上传宠物照片', trigger: 'change' }
  ]
}

// 查看详情
const handleView = (row) => {
  detailData.value = { ...row }
  detailDialogVisible.value = true
}

// 获取宠物类型列表
const getPetTypes = async () => {
  try {
    const res = await request.get('/types/all')
    if (res.code === 200) {
      petTypes.value = res.data
    }
  } catch (error) {
    console.error('获取宠物类型列表失败:', error)
    ElMessage.error('获取宠物类型列表失败')
  }
}

// 格式化日期
const formatDate = (date) => {
  if (!date) return ''
  const d = new Date(date)
  const year = d.getFullYear()
  const month = String(d.getMonth() + 1).padStart(2, '0')
  const day = String(d.getDate()).padStart(2, '0')
  const hours = String(d.getHours()).padStart(2, '0')
  const minutes = String(d.getMinutes()).padStart(2, '0')
  const seconds = String(d.getSeconds()).padStart(2, '0')
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}

// 获取领养贴列表
const getPostList = async () => {
  loading.value = true
  try {
    const res = await request.get('/pet/petSearch', {
      params: {
        pageNum: currentPage.value,
        pageSize: pageSize.value,
        name: searchQuery.name,
        status: searchQuery.status,
        type: searchQuery.type
      }
    })
    if (res.code === 200 && res.data) {
      postList.value = res.data.list
      total.value = res.data.total
      
      if (postList.value.length === 0 && currentPage.value > 1) {
        currentPage.value--
        await getPostList()
        return
      }
    } else {
      postList.value = []
      total.value = 0
      ElMessage.warning('未找到相关数据')
    }
  } catch (error) {
    console.error('获取领养贴列表失败:', error)
    ElMessage.error('获取列表失败')
    postList.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  getPostList()
}

// 清除搜索条件
const handleClear = () => {
  Object.keys(searchQuery).forEach(key => {
    searchQuery[key] = ''
  })
  currentPage.value = 1
  getPostList()
}

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
  getPostList()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  getPostList()
}

// 添加领养贴
const handleAdd = () => {
  dialogType.value = 'add'
  Object.keys(form).forEach(key => {
    form[key] = key === 'age' ? 0 : key === 'gender' ? 'male' : key === 'status' ? 'available' : null
  })
  dialogVisible.value = true
}

// 编辑领养贴
const handleEdit = (row) => {
  dialogType.value = 'edit'
  Object.assign(form, row)
  dialogVisible.value = true
}

// 提交表单
const handleSubmit = () => {
  if (!formRef.value) return
  
  formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const res = await request.post('/pet/petAdd', form)
        if(res.code === 200) {
          ElMessage.success(dialogType.value === 'add' ? '发布成功' : '编辑成功')
          dialogVisible.value = false
          currentPage.value = 1
          getPostList()
        } else {
          ElMessage.error(res.msg || '操作失败')
        }
      } catch (error) {
        console.error('操作失败:', error)
        ElMessage.error('操作失败')
      }
    }
  })
}

// 删除领养贴
const handleDelete = (row) => {
  ElMessageBox.confirm(
    '确认删除该领养信息吗？',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(async () => {
    try {
      const res = await request.delete('/pet/petDelete', {
        data: { id: row.id }
      })
      if(res.code === 200) {
        ElMessage.success('删除成功')
        getPostList()
      } else {
        ElMessage.error(res.msg || '删除失败')
      }
    } catch (error) {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  })
}

// 更改状态（上架/下架）
const handleStatusChange = (row) => {
  const newStatus = row.status === 'offline' ? 'available' : 'offline'
  const action = row.status === 'offline' ? '上架' : '下架'
  
  ElMessageBox.confirm(
    `确认${action}该领养信息吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(async () => {
    try {
      const res = await request.post('/pet/petAdd', {
        ...row,
        status: newStatus
      })
      if(res.code === 200) {
        ElMessage.success(`${action}成功`)
        getPostList()
      } else {
        ElMessage.error(res.msg || `${action}失败`)
      }
    } catch (error) {
      console.error(`${action}失败:`, error)
      ElMessage.error(`${action}失败`)
    }
  })
}

// 图片上传相关
const beforeImageUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt5M = file.size / 1024 / 1024 < 5

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  if (!isLt5M) {
    ElMessage.error('图片大小不能超过 5MB!')
    return false
  }
  return true
}

const handleImageSuccess = (response) => {
  if (response.code === 200) {
    form.image = response.data
    ElMessage.success('图片上传成功')
  } else {
    ElMessage.error(response.msg || '图片上传失败')
  }
}

const handleImageRemove = () => {
  form.image = ''
}

onMounted(() => {
  getPetTypes()
  getPostList()
})
</script>

<style scoped lang="scss">
.adoption-post-container {
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.search-container {
  margin-bottom: 20px;
}

.add-btn {
  background-color: #2f3447;
  border-color: #2f3447;
  color: #fff;
  &:focus {
    outline: none !important;
  }
}

.add-btn:hover {
  background-color: #383d52;
  border-color: #383d52;
}

.search-btn {
  background-color: #f9dee1;
  border-color: #f9dee1;
  color: #2f3447;
  &:focus {
    outline: none !important;
  }
}

.search-btn:hover {
  background-color: #f5c5cb;
  border-color: #f5c5cb;
}

.clear-btn {
  background-color: #ff4d4f;
  border-color: #ff4d4f;
  &:focus {
    outline: none !important;
  }
}

.clear-btn:hover {
  background-color: #ff7875;
  border-color: #ff7875;
}

.custom-table {
  margin: 20px 0;
  border-radius: 8px;
  overflow: hidden;
}

.pet-image {
  width: 60px;
  height: 60px;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s;
}

.pet-image:hover {
  transform: scale(1.1);
}

.edit-btn, .submit-btn {
  background-color: #2f3447;
  border-color: #2f3447;
  &:focus {
    outline: none !important;
  }
}

.edit-btn:hover, .submit-btn:hover {
  background-color: #383d52;
  border-color: #383d52;
}

.view-btn {
  background-color: #909399;
  border-color: #909399;
  color: #fff;
  &:focus {
    outline: none !important;
  }
}

.view-btn:hover {
  background-color: #a6a9ad;
  border-color: #a6a9ad;
}

.status-btn {
  min-width: 80px;
  &:focus {
    outline: none !important;
  }
}

.delete-btn {
  background-color: #ff4d4f;
  border-color: #ff4d4f;
  &:focus {
    outline: none !important;
  }
}

.delete-btn:hover {
  background-color: #ff7875;
  border-color: #ff7875;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.pet-uploader {
  :deep(.el-upload) {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: all 0.3s;

    &:hover {
      border-color: #409eff;
    }
  }

  :deep(.el-upload--picture-card) {
    background-color: #fbfdff;
    border: 1px dashed #c0ccda;
    border-radius: 6px;
    box-sizing: border-box;
    width: 148px;
    height: 148px;
    cursor: pointer;
    line-height: 146px;
    vertical-align: top;

    &:hover {
      border-color: #409eff;
      color: #409eff;
    }
  }

  .pet-image {
    width: 146px;
    height: 146px;
    display: block;
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.cancel-btn {
  background-color: #f9dee1;
  border-color: #f9dee1;
  color: #2f3447;
  &:focus {
    outline: none !important;
  }
}

.cancel-btn:hover {
  background-color: #f5c5cb;
  border-color: #f5c5cb;
}

.detail-dialog {
  :deep(.el-dialog__body) {
    padding: 0;
  }
}

.detail-content {
  display: flex;
  min-height: 500px;
}

.detail-left {
  width: 300px;
  background: #f8f9fa;
  padding: 30px;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 20px;
}

.detail-image {
  width: 240px;
  height: 240px;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.image-error {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f5f7fa;
  font-size: 24px;
  color: #909399;
}

.pet-status {
  margin-top: 10px;
}

.detail-right {
  flex: 1;
  padding: 30px;
}

.pet-name {
  font-size: 24px;
  font-weight: 600;
  color: #2c3e50;
  margin: 0 0 24px 0;
}

.info-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 20px;
  margin-bottom: 30px;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 8px;
}

.info-item {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.label {
  font-size: 14px;
  color: #909399;
}

.value {
  font-size: 16px;
  color: #2c3e50;
  font-weight: 500;
}

.info-section {
  margin-bottom: 24px;

  h4 {
    font-size: 16px;
    color: #606266;
    margin: 0 0 12px 0;
    font-weight: 600;
  }

  .description {
    font-size: 14px;
    color: #606266;
    line-height: 1.6;
    margin: 0;
    padding: 16px;
    background: #f8f9fa;
    border-radius: 8px;
    min-height: 80px;
  }
}

.time-info {
  margin-top: 30px;
  padding-top: 20px;
  border-top: 1px solid #ebeef5;
  display: flex;
  gap: 40px;
}

.time-item {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.time-label {
  font-size: 12px;
  color: #909399;
}

.time-value {
  font-size: 14px;
  color: #606266;
}
.pet-type-tag {
  font-size: 12px;
  color:skyblue;
  font-weight:bold;
}
</style>